package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartpro.mis.modular.business.service.IThirdPartyUserService;
import com.smartpro.mis.modular.business.service.IUserService;
import com.smartpro.mis.modular.system.model.ThirdPartyUser;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/service/wechat")
@Slf4j
public class WxLoginController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private IThirdPartyUserService thirdPartyUserService;
    @Autowired
    private IUserService userService;

    /**
     * 微信网页授权流程:
     * 1. 用户同意授权,获取 code
     * 2. 通过 code 换取网页授权 access_token
     * 3. 使用获取到的 access_token 和 openid 拉取用户信息
     */


    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        String url = "http://t.machengshuang.cn/wechat/userInfo";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    @ApiOperation(value = "微信用户登录")
    @ApiImplicitParam(name = "jsonObject",value = "授权code,跳转state")
    @GetMapping("/wechatLogin")
    @ResponseBody
    public Object wechatLogin(@RequestBody JSONObject jsonObject) throws Exception {
        JSONObject res = new JSONObject();
        String code =jsonObject.getString("code");
        String returnUrl = jsonObject.getString("state");
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        WxMpUser wxMpUser;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            wxMpUser = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        Map query = new HashMap();
        query.put("openId",openId);
        List <ThirdPartyUser> thirdPartyUserList = this.thirdPartyUserService.selectByMap(query);
        if(null != thirdPartyUserList && thirdPartyUserList.size()>0){
            ThirdPartyUser thirdPartyUser = thirdPartyUserList.get(0);
            res.put("userInfo",userService.selectById(thirdPartyUser.getUserId()));
        }
        res.put("openId",wxMpOAuth2AccessToken.getOpenId());
        res.put("access_token",wxMpOAuth2AccessToken.getAccessToken());
        res.put("refresh_token",wxMpOAuth2AccessToken.getRefreshToken());
        res.put("expireTime",wxMpOAuth2AccessToken.getExpiresIn());

//        return "redirect:" + returnUrl + "?openid=" + openId;
        return new ResponseBean(200,"login success", res);
    }





    public Object getAccessToken(@RequestParam(name = "code") String code, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(code)) {
            return new ResponseBean(400, "code不存在", null );
        }
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            String accessToken = wxMpOAuth2AccessToken.getAccessToken();
            // 获取用户微信账户信息
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
            if (StringUtils.isBlank(wxMpUser.getOpenId())) {
                return new ResponseBean(400, "用户数据不存在", null );
            }
            return new ResponseBean(200, "operation success", wxMpUser );
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.info("授权异常：{}", e);
            return new ResponseBean(401, "授权登录失败", e.getError() );
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(400, "登录失败", e.getMessage() );
        }
    }

}
